package com.ygqh.baby.service.impl;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.excel.domain.OrderDetailSendEntity;
import com.ygqh.baby.handler.SendOrderDetailImportHandler;
import com.ygqh.baby.mapper.YgOrderSendDetailMapper;
import com.ygqh.baby.model.OrderSendDetailSearchParam;
import com.ygqh.baby.model.OrderSendParam;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.YgLogisticsService;
import com.ygqh.baby.service.YgOrderDetailService;
import com.ygqh.baby.service.YgOrderSendDetailService;
import com.ygqh.baby.service.YgOrderService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class YgOrderSendDetailServiceImpl implements YgOrderSendDetailService {

    @Autowired
    private YgOrderSendDetailMapper ygOrderSendDetailMapper;

    @Autowired
    private YgOrderService ygOrderService;

    @Autowired
    private YgOrderDetailService ygOrderDetailService;

    @Autowired
    private YgLogisticsService ygLogisticsService;

    @Autowired
    private SendOrderDetailImportHandler sendOrderDetailImportHandler;


    @Override
    public List<YgOrderSendDetail> findBySubIds(Long[] subIds) {
        if (subIds == null || subIds.length == 0) {
            return Collections.emptyList();
        }
        YgOrderSendDetailExample example = new YgOrderSendDetailExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andSubIdIn(Arrays.asList(subIds));
        return ygOrderSendDetailMapper.selectByExample(example);
    }

    @Override
    public List<YgOrderSendDetail> findByOrderIds(Long[] orderIds) {
        if (orderIds == null || orderIds.length == 0) {
            return Collections.emptyList();
        }
        YgOrderSendDetailExample example = new YgOrderSendDetailExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andOrderIdIn(Arrays.asList(orderIds));
        return ygOrderSendDetailMapper.selectByExample(example);
    }

    @Override
    public int findCount() {
        YgOrderSendDetailExample example = new YgOrderSendDetailExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
        return ygOrderSendDetailMapper.countByExample(example);
    }

    @Override
    public YgOrderSendDetail findById(Long id) {
        return ygOrderSendDetailMapper.selectByPrimaryKey(id);
    }


    @Override
    public int save(YgOrderSendDetail ygOrderSendDetail) {
        return ygOrderSendDetailMapper.insertSelective(ygOrderSendDetail);
    }

    @Override
    public int update(YgOrderSendDetail ygOrderSendDetail) {
        return ygOrderSendDetailMapper.updateByPrimaryKeySelective(ygOrderSendDetail);
    }

    @Override
    public int addBatch(List<YgOrderSendDetail> detailList) {
        if (CollectionUtils.isEmpty(detailList)) {
            return 0;
        }
        return ygOrderSendDetailMapper.addBatch(detailList);
    }

    @Override
    public ResultSet<YgOrderSendDetail> search(OrderSendDetailSearchParam sendDetailSearchParam) {
        int i = ygOrderSendDetailMapper.countSuper(sendDetailSearchParam);
        List<YgOrderSendDetail> detailList;
        if (i > 0) {
            detailList = ygOrderSendDetailMapper.selectSuper(sendDetailSearchParam);
        } else {
            detailList = Collections.emptyList();
        }
        return new ResultSet<>(i, detailList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message sendOrder(OrderSendParam sendParam) {

        YgOrderSendDetail sendDetail = ygOrderSendDetailMapper.selectByPrimaryKey(sendParam.getDetailId());
        if (!OrderStatus.WaitingSend.name().equals(sendDetail.getOrderStatus())) {
            return Message.error("订单状态有误，请核对订单状态。", sendDetail.getOrderStatus());
        }
        if (sendParam.getSendTime() == null) {
            sendParam.setSendTime(new Date());
        }
        sendDetail.setLogisticsCode(sendParam.getLogisticsCode());
        sendDetail.setLogisticsName(sendParam.getLogisticsName());
        sendDetail.setExpressCode(sendParam.getExpressCode());
        sendDetail.setRealSendTime(sendParam.getSendTime());
        sendDetail.setOrderStatus(OrderStatus.WaitingSign.name());
        ygOrderSendDetailMapper.updateByPrimaryKeySelective(sendDetail);

        //更新原单逻辑
        sendParam.setOrderId(sendDetail.getOrderId());
        sendParam.setDetailId(sendDetail.getOdId());
        updateSourceOrderSendStatus(sendParam);
        return Message.success(null);
    }

    @Override
    public Message closeSendOrderDetail(Long id, String remark, String handler) {
        YgOrderSendDetail sendDetail = ygOrderSendDetailMapper.selectByPrimaryKey(id);

        sendDetail.setOrderStatus(OrderStatus.TradeClosed.name());
        sendDetail.setRemark(remark);
        sendDetail.setUpdateBy(handler);
        sendDetail.setUpdateTime(new Date());
        ygOrderSendDetailMapper.updateByPrimaryKeySelective(sendDetail);
        return Message.success(null);
    }

    @Override
    public List<YgOrderSendDetail> findList(OrderSendDetailSearchParam sendDetailSearchParam) {
        return ygOrderSendDetailMapper.selectSuper(sendDetailSearchParam);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message sendOrderDetailBatch(List<OrderDetailSendEntity> sendList, String handler, Date updateTime) {
        sendOrderDetailImportHandler.checkSend(sendList);

        Map<Boolean, List<OrderDetailSendEntity>> sendMap = sendList.stream().collect(Collectors.groupingBy(detail -> StringUtil.isBlank(detail.getErrorMsg())));
        List<OrderDetailSendEntity> sendEntityList = sendMap.get(true);
        ygOrderSendDetailMapper.sendOrderDetailBatch(sendEntityList, handler, updateTime);

        List<YgLogistics> list = new ArrayList<>(sendEntityList.size());
        sendEntityList.forEach(detail -> {
            YgLogistics ygLogistics = new YgLogistics();
            ygLogistics.setOrderId(detail.getSourceOrderId().toString());
            ygLogistics.setExpressCode(detail.getExpressCode());
            ygLogistics.setExpressCompany(detail.getLogisticsName());
            ygLogistics.setLogisticsCode(detail.getLogisticsCode());
            ygLogistics.setSendTime(detail.getSendTime());
            ygLogistics.setAddress(detail.getSkuCode());
            list.add(ygLogistics);
        });

        ygOrderService.updateLogistics(list);
        List<OrderDetailSendEntity> errorList = sendMap.get(false);
        if (CollectionUtils.isNotEmpty(errorList)) {
            String errorMsg = sendMap.get(false).stream().map(OrderDetailSendEntity::getErrorMsg).toString();
            return Message.error(errorMsg, errorList);
        }
        return Message.success(null);
    }

    @Override
    public boolean existed(Long orderId) {
        Assert.notNull(orderId, "orderId can't be null.");
        YgOrderSendDetailExample example = new YgOrderSendDetailExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        int count = ygOrderSendDetailMapper.countByExample(example);
        return count > 0;
    }

    @Override
    public int updateNeedSendTime(Long detailId, Date sendTime, String trueName, String remark) {
        YgOrderSendDetail orderSendDetail = new YgOrderSendDetail();
        orderSendDetail.setId(detailId);
        orderSendDetail.setNeedSendTime(sendTime);
        orderSendDetail.setUpdateBy(trueName);
        orderSendDetail.setUpdateTime(new Date());
        if(StringUtil.isBlank(remark)){
            remark = "更新应发货日期";
        }
        orderSendDetail.setRemark(remark);
        return ygOrderSendDetailMapper.updateByPrimaryKeySelective(orderSendDetail);
    }


    private void updateSourceOrderSendStatus(OrderSendParam sendParam) {
        YgOrder order = new YgOrder();
        order.setSendTime(sendParam.getSendTime());
        order.setOrderStatus(OrderStatus.WaitingSign);
        order.setOrderId(sendParam.getOrderId());
        ygOrderService.updateByOrderId(order);

        /**
         * 这里只适用 sendTargetSkuQuantity =1
         */
        YgOrderDetail orderDetail = new YgOrderDetail();
        orderDetail.setId(sendParam.getDetailId());
        orderDetail.setDetailStatus(OrderDetailStatus.WaitingSign);
        orderDetail.setSendMark(sendParam.getExpressCode());
        ygOrderDetailService.update(orderDetail);

        YgLogistics ygLogistics = new YgLogistics();
        ygLogistics.setOrderId(sendParam.getOrderId().toString());
        ygLogistics.setSendTime(sendParam.getSendTime());
        ygLogistics.setCreateTime(new Date());
        ygLogistics.setExpressCode(sendParam.getExpressCode());
        ygLogistics.setExpressCompany(sendParam.getLogisticsName());
        ygLogistics.setLogisticsCode(sendParam.getLogisticsCode());
        ygLogisticsService.save(ygLogistics);
    }

    @Override
    public int saveOrUpdate(YgOrderSendDetail ygOrderSendDetail) {
        int r = 0;
        if (ygOrderSendDetail.getId() != null) {
            r = this.update(ygOrderSendDetail);
        } else {
            r = this.save(ygOrderSendDetail);
        }
        return r;
    }

}

